<?php
/**
* Application level Controller
*
* This file is application-wide controller file. You can put all
* application-wide controller-related methods here.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link          http://cakephp.org CakePHP(tm) Project
* @package       app.Controller
* @since         CakePHP(tm) v 0.2.9
* @license       http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');

/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* @package		app.Controller
* @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {

	// added the debug toolkit
	// sessions support
	// authorization for login and logut redirect
	public $components = array(
		'Session',
		'Auth' => array(
			'loginAction' => array('admin' => false, 'controller' => 'users', 'action' => 'login'),
			'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
			'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
			'authError' => 'Você precisa estar logado para ver essa página.',
			'loginError' => 'Usuário ou senha inválido. Por favor, tente novamente.',
			'authorize' => array('Controller')
		));

		private $roles = array(
			'*' => 0,
			'cliente' => 1,
			'admin' => 2
		);

		// only allow the login controllers only
		public function beforeFilter() {
			$this->Auth->allow('login', 'home');

			if($this->params['admin']){
				$this->layout = 'admin';
			}

			if (isset($this->permissao['*'])) { //ver quais actions são liberadas pra todos
				$this->Auth->allow($this->permissao['*']);
			} else if(!isset($this->permissao)){ //se não tiver uma lista de permissões no controller, libera tudo
				$this->Auth->allow('*');
			}
		}

		public function isAuthorized($user) {
			// Admin can access every action
			if (isset($user['role']) && $user['role'] === 'admin') {
				return true;
			}

			//verifica no array de permissoes setado no controller se o usuario tem permissão para ver a action
			/*if (isset($this->permissao[$user['role']]) && in_array($this->action, $this->permissao[$user['role']])) {
			return true;
		}*/
		$rolePermitido = $this->recursive_array_search($this->action, $this->permissao);
		//debug($this->action);
		//debug($this->permissao);
		//debug($rolePermitido);
		$isAuthorized = $this->roles[$user['role']] >= $this->roles[$rolePermitido];
		//debug($isAuthorized);
		//debug($this->roles);

		if (isset($this->permissao[$user['role']]) && $isAuthorized) {
			return true;
		}

		// Default deny
		return false;
	}

	public function beforeRender() {
		if($this->layout == 'comprador'){
			$this->loadModel('Categoria');
			$menu = $this->Categoria->find('all');
			$this->set('menu', $menu);
		}

		if ($this->Session->check('Message')) {
			$flash = $this->Session->read('Message');

			if (isset($flash['default'])) {
				$flash['default']['element'] = 'alerta';
			} else if (isset($flash['good'])) {
				$flash['good']['element'] = 'sucesso';
			} else if (isset($flash['bad'])) {
				$flash['bad']['element'] = 'erro';
			}

			$this->Session->write('Message', $flash);
		}
	}

	public function setTitle($title){
		$this->set('title', $title);
	}

	public function recursive_array_search($needle,$haystack) {
		foreach($haystack as $key=>$value) {
			$current_key=$key;
			if($needle===$value OR (is_array($value) && $this->recursive_array_search($needle,$value) !== false)) {
				return $current_key;
			}
		}
		return false;
	}

}
